<template>
  <div style="height: auto" v-if="JouneryDayInfo != null && JouneryDayInfo.length > 0">
    <div class="nav_li" id="nav_li" :class="{ nav_li_fiexd: isSubNavFixed }">
      <!--div class="bot" v-if="skuDetail.isVip && userInfo.id">立即预订</div && isVip -->
      <div class="num"><i class="iconfont icon-lianxiwomen"></i></div>
      <div class="nav_left">
        <div class="li" :data-key="0" :class="{ active: activeSubNav === 0 }" @click="tabClick(0, 1, 'feature')">行程特色</div>
        <div class="li" :data-key="1" :class="{ active: activeSubNav === 1 }" @click="tabClick(1, 1, 'introduction')">行程详情</div>
        <div class="li" :data-key="2" :class="{ active: activeSubNav === 2 }" @click="tabClick(2, 1, 'fee')">费用说明</div>
        <div class="li" :data-key="3" :class="{ active: activeSubNav === 3 }" @click="tabClick(3, 1, 'booking')">预订须知</div>
        <div class="li" :data-key="4" :class="{ active: activeSubNav === 4 }" @click="tabClick(4, 1, 'download')" v-if="JouneryGroupInfo.Cmsfiles.length > 0">文档下载</div>
      </div>
    </div>

    <div class="main2" style="padding-top: 0px; min-height: 300px">
      <!-- 一、行程特色 -->
      <TripSection sectionId="feature" sectionTitle="行程特色" iconClass="fa fa-plane" :JouneryGroups="JouneryGroups">
        <template #default="{ JouneryGroupInfo }">
          <!-- 收客须知 开始 -->
          <div class="info_box" v-if="JouneryGroupInfo.Instructions != '' && JouneryGroupInfo.isVip">
            <div class="main2_right_m2_title trip_nav_m"><Icon type="ios-bookmark" />收客须知（直客不显示）</div>
            <div class="main2_right_m2_m">
              <p class="info_paragraph" v-show="JouneryGroupInfo.Instructions != ''" v-html="JouneryGroupInfo.Instructions"></p>
            </div>
          </div>
          <!-- 行程特点 开始 -->
          <InfoBox boxTitle="行程特点" iconType="ios-bookmark" :content="JouneryGroupInfo.Summary" />
        </template>
      </TripSection>

      <!-- 二、行程介绍 -->
      <ul class="u_route" id="introduction">
        <div class="main2_left">
          <div class="main2_left_t" style="background: none; height: 1px; line-height: 1px"></div>
          <div class="trip_m" style="display: none">
            <div class="li" :class="k === 0 ? 'active' : ''" v-for="(JouneryInfo, k) in JouneryDayInfo" :key="k">
              <span>第{{ JouneryInfo.Days }}天</span>
            </div>
          </div>
        </div>
        <div class="main2_right" v-for="(JouneryGroupInfo, index) in JouneryGroups" :key="index" :class="index == 0 ? 'wrap-box' : 'wrap-box hide'" find-trip-center>
          <div class="main2_right_m2 active">
            <!-- 五 行程介绍 开始 -->
            <div class="info_box" v-if="!!JouneryDayInfo">
              <div class="main2_right_m2_title trip_nav_m"><Icon type="ios-bookmark" />详细行程</div>
              <div class="main2_right_m3_m stroke">
                <div class="main2_right_m3_m1" v-for="(JouneryInfo, k) in JouneryDayInfo" :key="k">
                  <div class="main2_right_m3_m1_l">
                    <p>Day</p>
                    <span>{{ JouneryInfo.Days > 9 ? JouneryInfo.Days : '0' + JouneryInfo.Days }}</span>
                  </div>
                  <div class="main2_right_m3_m1_r">
                    <h2>
                      <div class="placecontent">
                        <span class="startp" v-for="(JouneryProductTravelType, indexType) in JouneryInfo.ProductTravelTypes" :key="indexType">
                          <i :class="'iconfont icon-vehicle-' + JouneryProductTravelType.Type" v-show="indexType > 0"></i>
                          <span>{{JouneryProductTravelType.TreeName}}</span>
                        </span>
                      </div>
                    </h2>
                    <div class="dinner" style="margin-top: 8rpx; padding-right: 0" v-if="JouneryInfo.viewspots.length > 0">
                      <i class="iconfont icon-daohangxianlu fl" style="float: left; display: inline-block; vertical-align: -10px; margin-right: 8px"></i>
                      <div class="breakcon" style="padding-right: 0">
                        <span class="breakfast">景点：</span>
                        <span v-for="(viewspot, indexVs) in JouneryInfo.viewspots" :key="indexVs">
                          <i
                            class="iconfont icon-dian"
                            style="background: #333; font-size: 18px; vertical-align: -2px; -webkit-background-clip: text; -webkit-text-fill-color: transparent"
                            v-show="indexVs > 0"
                          ></i>
                          <span>{{ viewspot.name }}</span>
                        </span>
                      </div>
                    </div>

                    <div class="dinner">
                      <i class="iconfont icon-meal fl" style="vertical-align: -10px; margin-right: 8px"></i>
                      <div class="breakcon" v-if="JouneryInfo.Lunch === ''"><span class="breakfast">用餐：</span>自理<i class="iconfont icon-hotel fl"></i></div>
                      <div class="breakcon" v-if="JouneryInfo.Lunch != ''">
                        <span class="breakfast">用餐：</span>
                        <span class="lunch" v-for="(lunch, index) in JouneryInfo.Lunch" :key="index">
                          {{lunch.Name}}
                          <i :class="'iconfont icon-' + lunch.Type + '-2'" style="font-size: 16px; margin-right: 10rpx; vertical-align: -2px"></i>
                        </span>
                      </div>
                      <div class="jiudiancon">
                        <i class="iconfont icon-hotel fl" style="vertical-align: -10px; margin-right: 8px"></i>
                        <span class="breakfast">酒店：</span><span>{{ JouneryInfo.HotelList }}</span>
                      </div>
                    </div>

                    <div class="travelcontent">
                      <p class="traveldec" v-html="JouneryInfo.Content"></p>
                      <!-- 轮播开始 v-show="travelActive ==  k"-->
                      <div v-show="JouneryInfo.JouneryImgInfo.length > 0" style="padding: 0 5px">
                        <div class="swiper-slide" v-for="(ImgInfo, index) in JouneryInfo.JouneryImgInfo" :key="index">
                          <img :src="ImgInfo.ImgUrl" class="slideimg" onerror="onerror=null;src='about:blank'" />
                          <p>{{ ImgInfo.TreeName }}</p>
                        </div>
                      </div>
                      <!-- 轮播结束 -->
                    </div>
                  </div>
                </div>
              </div>
            </div>
            <!-- 五 行程介绍 结束 -->
          </div>
        </div>
        <div class="clear"></div>
      </ul>

      <!-- 三、费用说明 -->
      <TripSection sectionId="fee" sectionTitle="费用说明" iconClass="fa fa-futbol" :JouneryGroups="JouneryGroups">
        <template #default="{ JouneryGroupInfo }">
          <!-- 七、费用包含-->
          <InfoBox boxTitle="费用包含" iconType="ios-bookmark" :content="JouneryGroupInfo.CostInclude" />

          <!-- 八、费用不含-->
          <InfoBox boxTitle="费用不含" iconType="ios-bookmark" :content="JouneryGroupInfo.CostNotInclude" />
        </template>
      </TripSection>

      <!-- 四、预订说明 -->
      <TripSection sectionId="booking" sectionTitle="预订须知" iconClass="fa fa-tasks" :JouneryGroups="JouneryGroups">
        <template #default="{ JouneryGroupInfo }">
          <!-- 4.1、注意事项-->
          <InfoBox boxTitle="注意事项" iconType="ios-bookmark" :content="JouneryGroupInfo.Notice" />

          <!-- 4.2、特别提示 -->
          <InfoBox boxTitle="特别提示" iconType="ios-bookmark" :content="JouneryGroupInfo.Warm_prompt" />

          <!-- 4.3、购物安排 -->
          <InfoBox boxTitle="购物安排" iconType="ios-bookmark" :content="JouneryGroupInfo.Shopping_explanation" />
        </template>
      </TripSection>

      <!-- 五、文档附件 -->
      <TripSection sectionId="download" sectionTitle="文档附件" iconClass="fa fa-tasks" :JouneryGroups="JouneryGroups" v-if="JouneryGroupInfo.Cmsfiles.length > 0">
        <template #default="{ JouneryGroupInfo }">
          <!-- 5.1、文档附件-->
          <div class="main2_right">
            <div class="main2_right_m2_title"><Icon type="ios-bookmark" />文档附件</div>
            <div class="main2_right_m3">
              <p v-for="(rows, index) in JouneryGroupInfo.Cmsfiles" :key="index">
                <i class="fa fa-file-pdf-o" style="color: red;" v-if="rows.extend.indexOf('pdf')>0"></i>
                <i class="fa fa-file-word-o" v-else></i>
                <span class="file-name" @click="docDownload" :data-path="rows.realpath" :data-id="rows.id" :data-extend="rows.extend" style="">{{rows.name}}</span>
                <span class="down-load" @click="docDownload" :data-path="rows.realpath" style="color: red;">下载</span>
              </p>
            </div>
          </div>
          <div class="clear"></div>
        </template>
      </TripSection>
    </div>
  </div>
</template>

<script>
import TripSection from './components/tripSection.vue';
import InfoBox from './components/infoBox.vue';
import common from '@/plugins/common';
import { goodsComment, goodsCommentNum, readTravelAgency } from '@/api/member.js';
import { parseTravelTypes, parseViewspots, parseTravelPhotos, parsetLunchInfo } from '@/components/cruise/js/detail.js';
import { setupTravelNavigation } from '@/components/cruise/js/navi.js';

export default {
  name: 'ShowGoodsDetail',
  components: { TripSection, InfoBox },
  props: {
    detail: {
      type: Object,
      default: null,
    },
  },
  data() {
    return {
      // 评论相关数据
      // 存储评论列表
      commentList: [],
      // 评论请求参数
      commentParams: {
        // 当前页码，初始为第1页
        pageNumber: 1,
        // 每页显示的评论数量，初始为10条
        pageSize: 10,
        // 评论等级筛选条件，初始为空
        grade: '',
        // 商品ID，初始为空
        goodsId: '',
      },
      // 不同等级评论的数量统计
      commentTypeNum: {},
      // 评论总数
      commentTotal: 0,

      // 产品详情相关数据
      // 用户是否为VIP的标志
      isVip: false,
      // 行程分组信息
      JouneryGroups: [],
      JouneryGroupInfo: {},
      // 行程日信息
      JouneryDayInfo: {},
      // 文档文件信息
      Cmsfiles: {},
      // 旅行社信息
      travelAgency: {},
      // 产品经理信息
      ProductManager: '',
      // 当前激活的行程索引，初始为 -1
      travelActive: -1,
      // 用户信息
      userInfo: {},
      // 高度设置，初始为500px
      height: '500px',
      // 子导航栏是否固定的标志
      isSubNavFixed: false,
      // 当前激活的子导航栏索引，初始为0
      activeSubNav: 0,
      // 当前激活的日期导航栏索引，初始为0
      activeDayNav: 0,
    };
  },
  /**
   * 计算属性，用于获取商品详情信息
   * @returns {Object|null} 商品详情信息，如果存在则返回，否则返回 null
   */
  computed: {
    skuDetail() {
      // 从 props 的 detail 对象中获取 result 属性
      return this.detail.result;
    },
  },
  mounted() {
    // 登录会员本地缓存
    if (this.Cookies.getItem("userInfo")) {
      this.userInfo = JSON.parse(this.Cookies.getItem("userInfo"));
    }

    // 手动设置详情高度，解决无法撑开问题
    this.$nextTick(async () => { 
      await this.init();
      //setTimeout(this.changeHeight('itemIntroGoods'), 2000);
      await this.ready();
    });

  },
  methods: {
    // 初始化数据
    init() {
      this.onLoadProductInfo();
      this.onLoadJouneryGroups();
      this.buildJouneryDayInfo();
      this.buildTravelAgency();
    },

    // 加载产品信息
    async onLoadProductInfo() {
      const cmsArticle = this.skuDetail;
      if (!cmsArticle) return;

      this.isVip = this.skuDetail.isVip || false;

      //三、行程天数
      this.JouneryGroupInfo['Days'] = cmsArticle['days'];
      this.JouneryGroupInfo['Nights'] = cmsArticle['nights'];
      //四、行程特色
      this.JouneryGroupInfo['Summary'] = cmsArticle['summary'];
      //五、费用包含
      this.JouneryGroupInfo['CostInclude'] = cmsArticle['expenseContain'];
      //六、费用不含
      this.JouneryGroupInfo['CostNotInclude'] = cmsArticle['expenseNcontain'];
      //七、注意事项
      this.JouneryGroupInfo['Notice'] = cmsArticle['notice'];
      //八、特别提示
      this.JouneryGroupInfo['Warm_prompt'] = cmsArticle['warmPrompt'];
      //九、购物安排
      this.JouneryGroupInfo['Shopping_explanation'] = cmsArticle['shoppingExplanation'];
      //十、自费补充协议
      this.JouneryGroupInfo['Selfpaying_explanation'] = cmsArticle['selfpayingExplanation'];
      //十一、接待旅行社信息
      this.JouneryGroupInfo['Reception_explanation'] = cmsArticle['receptionExplanation'];
      //十五、附件下载
      this.JouneryGroupInfo['Cmsfiles'] = cmsArticle['cmsFiles'] || [];
      //十七、收客计调
      this.JouneryGroupInfo['ProductManager'] = cmsArticle['map'];
      //十八、收客计调
      this.JouneryGroups.push(this.JouneryGroupInfo);
    },

    // 加载行程分组
    async onLoadJouneryGroups() {
      const cmsArticle = this.skuDetail;
      if (!cmsArticle) return;

      const routes = cmsArticle.routes;
      const JouneryDetail = [];
      const swiperSlidebox = [];

      if (!routes || routes.length <= 0) {
        return;
      }

      const days = cmsArticle.days;
      for (let i = 0; i < days; i++) {
        const itm = routes[i];
        const travelTypes = parseTravelTypes(itm.traffic);
        const travelPhotos = parseTravelPhotos(itm.photos);
        const viewspots = parseViewspots(itm.viewspot);

        JouneryDetail.push({
          Days: i + 1,
          ProductTravelTypes: travelTypes,
          Breakfast: itm.breakfast,
          HaveLunch: itm.lunch,
          Dinner: itm.dinner,
          HotelList: itm.stay,
          viewspots,
          Content: itm.detail,
          JouneryImgInfo: travelPhotos,
        });
      }

      //行程天数
      this.JouneryGroupInfo['JouneryDetail'] = JouneryDetail;

      this.JouneryGroups.push(this.JouneryGroupInfo);
    },

    /**
     * 生成详细行程
     */
    buildJouneryDayInfo() {
      const { JouneryGroups } = this;
      const JouneryDayInfo = this.generateJouneryDayInfo(JouneryGroups);
      this.JouneryDayInfo = JouneryDayInfo;
    },

    /**
     * 生成行程日信息数组
     * @param {Array} JouneryGroups 行程组数组
     * @returns {Array} 行程日信息数组
     */
    generateJouneryDayInfo(JouneryGroups) {
      const JouneryDayInfo = [];
      for (let i = 0; i < JouneryGroups.length; i++) {
        const JouneryGroupInfo = JouneryGroups[i];
        const dailyJourneys = this.processJouneryGroup(JouneryGroupInfo);
        JouneryDayInfo.push(...dailyJourneys);
        // 设计缺陷只支持一个行程
        break;
      }
      return JouneryDayInfo;
    },

    /**
     * 处理单个行程组，生成每日行程信息
     * @param {Object} JouneryGroupInfo 行程组信息
     * @returns {Array} 每日行程信息数组
     */
    processJouneryGroup(JouneryGroupInfo) {
      const JouneryDetail = JouneryGroupInfo.JouneryDetail;
      const dailyJourneys = [];
      for (let j = 0; j < JouneryDetail.length; j++) {
        const Detail = JouneryDetail[j];
        const JouneryInfo = this.processDailyJourney(Detail);
        dailyJourneys.push(JouneryInfo);
      }
      return dailyJourneys;
    },

    /**
     * 处理单个每日行程，生成单个行程信息对象
     * @param {Object} Detail 每日行程详情
     * @returns {Object} 单个行程信息对象
     */
    processDailyJourney(Detail) {
      const JouneryInfo = { ...Detail };
      this.filterUnneededProperties(JouneryInfo);
      JouneryInfo.Lunch = parsetLunchInfo(Detail);
      return JouneryInfo;
    },

    /**
     * 过滤不需要的属性
     * @param {Object} JouneryInfo 行程信息对象
     */
    filterUnneededProperties(JouneryInfo) {
      ['Breakfast', 'HaveLunch', 'Dinner'].forEach((key) => {
        delete JouneryInfo[key];
      });
    },
    //----------buildJouneryDayInfo--------end--------------------------------


    // 构建报名单位信息
    /**
     * 收客单位
     */
    buildTravelAgency: function () {
      var me = this;
      //----------------------------------------------
      var share = common.getQueryString('share');
      var param = {};
      var user = this.userInfo;
      //测试
      if (process.env.NODE_ENV === 'development' && !share) {
        //share = 'f0ca431a79eddbac0179ee99a84d0061'
      }

      param.id = share || user.id || '';
      if (param.id === '') {
        console.info('收客单位--未获取到会员编号。');
        me.travelAgency = '';
        return;
      }

      readTravelAgency(param).then((res) => {
        var travelAgency = {};
        if (res && res.success) {
          var data = res.result || {};
          var state = data.state || '';
          if ('1' === state) {
            travelAgency = {
              title: data.corpName,
              linkman: data.name,
              tel: data.tel,
            };
          }
        }
        if (JSON.stringify(travelAgency) === '{}') {
          me.travelAgency = '';
        } else {
          me.travelAgency = travelAgency;
        }
      });
    },

    // 产品详情和评价之间的tab切换
    tabClick(name, type, id) {
      if (type == '1') {
        if (!id) return;
        this.activeSubNav = name;
        const element = $(`#${id}`).offset().top;
        const offset = name === 0 ? 105 : 110;
        $('html,body').animate({
          scrollTop: element - offset,
        });
      } else {
        this.routerTab = name;
      }
    },

    /**
     * 跳转附件下载
     */
    docDownload(e) {
      //https://www.jianshu.com/p/2ff6c09b1da0
      var filepath = e.currentTarget.dataset.path
      // api.docDownload(filepath)
      window.location.href = this.$config.staticDomainURL + '/sys/common/static' + '/' + filepath;
    },

    /**
     * 行程导航
     */
    ready() {
      setupTravelNavigation();
    },
  },
};
</script>
